package com.vclee.fast.utils;

import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.vclee.fast.config.Constant;
import com.vclee.fast.utils.model.UniToken;
import com.vclee.fast.utils.exception.Assert;
import com.vclee.fast.utils.model.Bson;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

public class JwtUtils {

    /**
     * @param aesKey 设备的aesKey
     * @return accessToken
     */
    public static String createAccessToken(String aesKey) {
        UniToken token = new UniToken();
        token.setAesKey(aesKey);
        token.setLatestTime(System.currentTimeMillis());
        return CipherUtils.saltEncrypt(Bson.toString(token), Constant.UNIFY_CIPHER);
    }

    /**
     * 用户登录成功后刷新accessToken
     * @param userId 当前用户使用环境
     * @return accessToken
     */
    public static String updateAccessToken(Long userId) {
        UniToken token =  Objects.requireNonNull(getUniToken());
        token.setUserId(userId);
        token.setLatestTime(new Date().getTime());
        return CipherUtils.saltEncrypt(Bson.toString(token), Constant.UNIFY_CIPHER);
    }

    /**
     * 从请求中获取accessToken进行校验,并返回新的accessToken
     * @return accessToken
     */
    public static String refreshAccessToken() {
        UniToken token = Objects.requireNonNull(getUniToken());
        // FIXME 可以在这里校验token信息 LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        token.setLatestTime(System.currentTimeMillis());
        return CipherUtils.saltEncrypt(Bson.toString(token), Constant.UNIFY_CIPHER);
    }

    /**
     * 从上下文中获取请求信息
     * @return HttpServletRequest
     */
    public static HttpServletRequest getContextHttpServletRequest() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return attributes==null?null:((ServletRequestAttributes) attributes).getRequest();
    }
    public static HttpServletResponse getContextHttpServletResponse() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return attributes==null?null:((ServletRequestAttributes) attributes).getResponse();
    }

    /**
     * 将accessToken票据转为UniToken对象
     * @return UniToken 包含clientId,aesKey,userId等信息
     */
    private static UniToken getUniToken(){
        try {
            HttpServletRequest request = getContextHttpServletRequest();
            String accessToken = Objects.requireNonNull(request).getHeader("accessToken");
            String jsonString = CipherUtils.saltDecrypt(accessToken, Constant.UNIFY_CIPHER);
            return Bson.toClazz(jsonString,UniToken.class);
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 从交互信息里面获取用户ID
     * @return userId
     */
    public static Long getUserId() {
        UniToken token = getUniToken();
        return token==null?null:token.getUserId();
    }


    /**
     * 根据accessToken获取aesKey
     * @return aesKey
     */
    public static String getAesKey(){
        UniToken token = getUniToken();
        Assert.claim(Assert.isNull(token), HttpStatus.SC_BAD_REQUEST,"票据不合法");
        return Objects.requireNonNull(token).getAesKey();
    }



    /**
     * 获取当前请求的IP地址
     * @return ip地址
     */
    public static String getIpAddress() {
        HttpServletRequest request = Objects.requireNonNull(getContextHttpServletRequest());
        String ip = request.getHeader("x-forwarded-for");
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (!StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //使用代理，则获取第一个IP地址
        if (ip.indexOf(",") > 0 && ip.length() > 15) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }
}
